package com.yjc.drygoods.member.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.yjc.common.constant.AuthServerConstant;
import com.yjc.common.exception.BizCodeEnume;
import com.yjc.common.to.CouponTo;
import com.yjc.common.vo.MemberRespVo;
import com.yjc.drygoods.member.entity.MemberEntity;
import com.yjc.drygoods.member.exception.PhoneExitException;
import com.yjc.drygoods.member.exception.UserNameExitException;
import com.yjc.drygoods.member.feign.CouponFeignService;
import com.yjc.drygoods.member.interceptor.LoginUserInterceptor;
import com.yjc.drygoods.member.service.MemberService;
import com.yjc.drygoods.member.vo.MemberLoginVo;
import com.yjc.drygoods.member.vo.MemberRegistVo;
import com.yjc.drygoods.member.vo.SocialVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import com.yjc.common.utils.PageUtils;
import com.yjc.common.utils.R;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


/**
 * 会员
 *
 * @author yjc
 * @email yjc19979401754@126.com
 * @date 2022-08-19 23:16:26
 */
@Slf4j
@RefreshScope
@RestController
@RequestMapping("member/member")
public class MemberController {
    @Autowired
    private MemberService memberService;

    @Autowired
    CouponFeignService couponFeignService;


    /**
     * 获取所有的会员的信息
     */
    @GetMapping("/get/all/memberInfo")
    public R getAllMemberInfo() {
        List<MemberEntity> list = memberService.getAllMemberInfo();
        return R.ok().setData(list);
    }

    /**
     * 微博社交账号登录(第一次进入时会自动注册)
     */
    @PostMapping("/oauth2.0/weibo/login")
    public R weiboLogin(@RequestBody SocialVo socialVo) {

        MemberEntity member = memberService.weiboLogin(socialVo);
        if (member != null) {
            return R.ok().setData(member);
        } else {
            return R.error(BizCodeEnume.LOGINACCOUNT_OR_PASSWORD_EXCEPTION.getCodeException(), BizCodeEnume.LOGINACCOUNT_OR_PASSWORD_EXCEPTION.getMessageException());
        }
    }


    /**
     * 会员登录
     */
    @PostMapping("/login")
    public R login(@RequestBody MemberLoginVo memberLoginVo) {

        MemberEntity member = memberService.loginMember(memberLoginVo);
        if (member != null) {
            return R.ok().setData(member);
        } else {
            return R.error(BizCodeEnume.LOGINACCOUNT_OR_PASSWORD_EXCEPTION.getCodeException(), BizCodeEnume.LOGINACCOUNT_OR_PASSWORD_EXCEPTION.getMessageException());
        }

    }

    /**
     * 会员注册
     *
     * @return
     */
    @PostMapping("/regist")
    public R registMember(@RequestBody MemberRegistVo memberRegistVo) {

        try {
            memberService.registMember(memberRegistVo);
        } catch (UserNameExitException e) {
            return R.error(BizCodeEnume.USER_EXIST_EXCEPTION.getCodeException(), BizCodeEnume.USER_EXIST_EXCEPTION.getMessageException());
        } catch (PhoneExitException e) {
            return R.error(BizCodeEnume.PHONE_EXIST_EXCEPTION.getCodeException(), BizCodeEnume.PHONE_EXIST_EXCEPTION.getMessageException());
        }
        return R.ok();
    }


    @GetMapping("/many/list")
    public R manyMember() {
        R coupons = couponFeignService.manyCoupon();
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setNickname("yjc");
        return R.ok().put("members", memberEntity).put("coupons", coupons.get("coupons"));
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = memberService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        MemberEntity member = memberService.getById(id);

        return R.ok().put("member", member);
    }

    /**
     * 信息
     */
    @RequestMapping("/info")
    public R infoByParam(@RequestParam("id") Long id) {
        MemberEntity member = memberService.getById(id);

        return R.ok().put("member", member);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody MemberEntity member) {
        memberService.save(member);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody @Valid MemberEntity member, HttpSession session, BindingResult bindingResult, RedirectAttributes re) {
        if (bindingResult.hasErrors()) {
            //1.出现异常，返回注册页面
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            //(v1, v2) -> v1):解决流重名问题
            Map<String, String> errors = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (v1, v2) -> v1));
            return R.error().setData("手机号格式错误");
        }
        log.info("member:{}", member);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        member.setId(memberRespVo.getId());
        MemberEntity memberEntity = memberService.updateMemberMySqlAndRedisById(member);
        BeanUtils.copyProperties(memberEntity, memberRespVo);
        session.setAttribute(AuthServerConstant.LOGIN_USER, memberRespVo);
        return R.ok().setData(null);
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        memberService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 解绑微博社交帐号
     */
    @RequestMapping("/clearSocial")
    public R clearSocial(HttpSession session) {
        MemberRespVo memberRespVo = memberService.clearSocial();
        session.setAttribute(AuthServerConstant.LOGIN_USER, memberRespVo);
        return R.ok();
    }

    /**
     * 保存优惠券
     *
     * @param coupon
     * @return
     */
    @PostMapping("/save/coupon/member")
    public R saveCoupon(@RequestBody CouponTo coupon) {
        try {
            memberService.saveCoupon(coupon);
        } catch (Exception e) {
            log.info("message:{}", e.getMessage());
            return R.error().put("msg", e.getMessage());
        }
        return R.ok();
    }

}
